import React, { useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import { useGlobalContext } from "../../context/GlobalContext";
import IconLogo from "../../assets/logo.svg";
import "./index.css";
import { getApiUrl } from "../../config/api";

const LoginPage = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const navigate = useNavigate();
  const { login } = useGlobalContext();

  const handleLogin = async (e) => {
    e.preventDefault();

    // 表单验证
    if (!username || !password) {
      setError("请输入用户名和密码");
      return;
    }

    setLoading(true);
    setError("");

    try {
      // 调用登录API
      const response = await fetch(getApiUrl('/api/auth/login'), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: username,
          password: password,
        }),
      });

      if (!response.ok) {
        throw new Error("登录失败，请检查用户名和密码");
      }

      const data = await response.json();
      
      // 确保传入正确的用户信息
      login({ 
        id: data.user.id,          // 添加 id
        username: data.user.username,
        token: data.token,
        avatar: data.user.avatar,
        nickname: data.user.nickname
      });
      
      // 跳转首页
      navigate("/chat", { replace: true });
    } catch (error) {
      setError("登录失败，请稍后重试");
      console.error("Login error:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <img className="logo" src={IconLogo} alt="AI魔方" />
        <h2>欢迎登录</h2>
        <form onSubmit={handleLogin}>
          <div className="input-group">
            <input
              type="text"
              placeholder="用户名"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              disabled={loading}
            />
          </div>
          <div className="input-group">
            <input
              type="password"
              placeholder="密码"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              disabled={loading}
            />
          </div>
          {error && <div className="login-error">{error}</div>}
          <button type="submit" disabled={loading}>
            {loading ? "登录中..." : "登录"}
          </button>
        </form>
        <div className="login-footer">
          <Link to="/register">注册新账号</Link>
          <span className="separator">|</span>
          <a href="#forgot-password">忘记密码？</a>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;
